/**
 * 手机号隐私保护
 * 隐藏中间四位数字
 * @param mobile
 * @returns {*}
 */
export function secrecyMobile(mobile: string | number): string {
  mobile = String(mobile)
  if (!/\d{11}/.test(mobile)) {
    return mobile
  }
  return mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

/**
 * 随机生成指定长度的字符串
 * @param length
 * @returns {string}
 */
export function randomString(length = 32): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const maxPos = chars.length
  let _string = ''
  for (let i = 0; i < length; i++) {
    _string += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return _string
}

// 生成随机简体中文字符的函数
function getRandomChsChar() {
  const CHS_RANGE_START = 0x4E00 // 简体中文编码范围开始
  const CHS_RANGE_END = 0x9FA5 // 简体中文编码范围结束
  // 生成 CHS_RANGE_START 和 CHS_RANGE_END 之间的随机整数
  const randomCharCode
    = Math.floor(Math.random() * (CHS_RANGE_END - CHS_RANGE_START + 1)) + CHS_RANGE_START

  // 将随机整数转换为字符
  return String.fromCharCode(randomCharCode)
}

// 生成指定长度的随机简体中文字符串
export function getRandomChsString(length: number) {
  let result = ''
  for (let i = 0; i < length; i++) {
    result += getRandomChsChar()
  }
  return result
}

export const hashCode = function (str: string) {
  let hash = 0
  let i
  let chr
  let len
  if (str.length === 0) return hash
  for (i = 0, len = str.length; i < len; i++) {
    chr = str.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0 // Convert to 32bit integer
  }
  return hash
}
